package org.example.service.utils;

import com.alibaba.fastjson2.JSONObject;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Component
public class FileUploadUtils {

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.folderName:bank}")
    private String folderName;

    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.huadongZheJiang2());

    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    /**
     * 上传文件
     * @param file
     * @return
     */
    public DefaultPutRet upload(MultipartFile file,String key){
        try {
            return upload(file.getInputStream(),key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传文件
     * @param inputStream
     * @param key
     * @return
     */
    public DefaultPutRet upload(InputStream inputStream, String key){
        String upToken = this.getUpToken();
        DefaultPutRet defaultPutRet = null;
        //解析上传成功的结果
        try {
            if (StringUtils.isNotBlank(key) && !key.startsWith(folderName)){
                key = folderName +"/" + key;
            }
            Response response = uploadManager.put(inputStream, key, upToken,null,null);
            defaultPutRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defaultPutRet;
    }

    /**
     * 获取token
     * @return
     */
    public String getUpToken(){
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    /**
     * 上传文件
     * @param file
     * @param key
     * @return
     */
    public DefaultPutRet upload(File file,String key){
        String upToken = this.getUpToken();
        DefaultPutRet defaultPutRet = null;
        //解析上传成功的结果
        try {
            if (StringUtils.isNotBlank(key) && !key.startsWith(folderName)){
                key = folderName +"/" + key;
            }
            Response response = uploadManager.put(file, key, upToken);
            defaultPutRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defaultPutRet;
    }
}
